import MDEditor from '@uiw/react-md-editor'
import { useState } from 'react'
import { useHistory } from 'react-router-dom'
import styles from './Create.module.css'
import { BASE_URL } from '../../constants'
const Create = () => {
  const history = useHistory()
  const [ content, setContent ] = useState('')
  const [ title , setTitle ] = useState('')
  const [ category , setCategory ] = useState('')
  const [ file, setFile ] = useState(null)
  const handleClick = () => {
    if (title.trim() === "") {
      alert("标题不能为空!")
      return
    }
    if (content.trim() === "") {
      alert("内容不能为空!")
      return
    }
    if (category.trim() === "") {
      alert("分类不能为空!")
      return
    }
    const fd = new FormData()
    fd.append('title', title)
    fd.append('content', content)
    fd.append('category', category)
    fd.append('thumbnail', file)
    fetch(`${BASE_URL}/articles`, {
      method: "POST",
      body: fd
    })
    .then(res => res.json())
    .then(res => {
      if (!res.status === "ok") alert("文章创建失败")
      else {
        alert("文章创建成功")
        history.push("/")
      }
    })
  }
  return (
    <div className={styles.create}>
      <div className={styles.title}>
        <span>新建文章</span>
        <button onClick={() => handleClick()}>发布</button>
      </div>
      <div>
        <div className={styles.formControl}>
          <label>标题</label>
          <input type="text" value={title} onChange={(e) => setTitle(e.target.value)}/>
        </div>
        <div className={styles.formControl}>
          <label>分类</label>
          <input type="text" value={category} onChange={e => setCategory(e.target.value)}/>
        </div>
        <div className={styles.upload}>
          <label htmlFor="file">{ file ? '已上传':'点击上传封面图'}</label>
          <input type="file" id="file" onChange={e => setFile(e.target.files[0])}/>
        </div>
        <MDEditor
          value={content}
          onChange={setContent}
        />
      </div>
    </div>
  )
}

export default Create